/*
 * Auther:Guan Junming <junming.guan at kisters.cn> Created:09-Oct-2011 17:55:44
 * Company:Kisters AG
 */
package cn.eclass.servlet.admin;

import cn.eclass.bean.api.IUserBean;
import cn.eclass.entity.UserEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.Helper;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;

/**
 *
 * @author Guan Junming <junming.guan at kisters.cn>
 */
public class User extends ActionFace {

    IUserBean bean = BeanFactory.factory.getUserBean();

    public void doUpdate() {
        int id = Integer.valueOf(request.getParameter("id"));
        UserEntity userEntity = bean.get(id);
        bean.update(form2Entity(userEntity));
        this.doIndex();
    }

    public void doCreate() {
        UserEntity userEntity = new UserEntity();
        bean.add(form2Entity(userEntity));
        this.doIndex();
    }

    /**
     * Ajax Out
     */
    public void doSelect() {
        int id = Integer.valueOf(request.getParameter("id"));
        UserEntity user = bean.get(id);
        out.print(new Gson().toJson(user));
    }

    public void doDelete() {
        int userId = Integer.valueOf(request.getParameter("id"));
        bean.delete(userId);
        this.doIndex();
    }

    @Override
    public void doIndex() {
        try {
            List<UserEntity> entities = bean.list();

            Field[] fields = UserEntity.class.getDeclaredFields();
            List<HashMap<String, String>> theFields = Helper.buildField(fields, module);

            request.setAttribute("entities", entities);
            request.setAttribute("fields", theFields);
            request.getRequestDispatcher(tableView).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Gift.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Gift.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private UserEntity form2Entity(UserEntity userEntity) {
        userEntity.setUsername(Helper.toUTF8(request.getParameter("username")));
        userEntity.setEmail(Helper.toUTF8(request.getParameter("email")));
        userEntity.setPassword(Helper.Md5(request.getParameter("password")));
        userEntity.setTelephone(Helper.toUTF8(request.getParameter("telephone")));
        userEntity.setPoints(Integer.valueOf(request.getParameter("points")));
        return userEntity;
    }
}
